package com.tastycai.curatorlock.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class HelloController {

    @Autowired
    private CuratorFramework client;

    @Autowired
    private InterProcessLock lock;

    private String lockPath = "/lock1";

    private int i = 0;

    @GetMapping("/hello")
    public String sayHello(){

        return "hello";
    }

    @GetMapping("/lock")
    public String test(String name) throws Exception {

        lock(name);
        return "after lock";
    }


    private void nolock(String name) throws Exception{

        readAndAdd(name);
    }
    private void lock(String name) throws Exception{

        InterProcessMutex lock1 = new InterProcessMutex(client, lockPath);

        //System.out.println(name + "before lock i=" + i);
        if ( lock1.acquire(20, TimeUnit.SECONDS) )
        {
            try
            {
                //System.out.println(name + "get lock");
                // do some work inside of the critical section here
                //Thread.sleep(10000);

                readAndAdd(name);
            }
            finally
            {
                lock1.release();
            }
        }
        //System.out.println(name + "after lock");
    }
    private void readAndAdd(String se) throws Exception{

        // System.out.println(i);
        // 先读取i
        int j = i;

        //Thread.sleep(10);

        ++i;

        // 再i+1并输出i
        int k;
        if ((k =i-j) != 1){

            System.out.println("并发有问题 k : " + k);
        }
    }
}
